package priv.hxm.serve.clientMsgHandler;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.log4j.Logger;

import priv.hxm.jdbcUtils.JDBCUtil;
import priv.mill.net.MyHttp;

/*
 * 聊天消息处理
 */
public class HandlerChat implements ClientMsgHandler {
	private static Logger logger = Logger.getLogger(HandlerChat.class);

	@Override
	public String doIt(MyHttp myHttp) { // 处理方法
		JuZi juzi = new JuZi();
		String data = (String) myHttp.getData();
		for (int i = 0; i < juzi.string.length; i++) {
			if (data.equals(juzi.string[i])) {
				for (int j = 0; j < juzi.string2.length;) {
					Random random = new Random();
					int nextInt = random.nextInt(7);
					return juzi.string2[nextInt];
				}
			}
		}
		List list = new ArrayList<>();
		List<Map<String, Object>> findAll = JDBCUtil
				.findAll("select * from question q join answer a on q.q_id=a.a_id");// 输入匹配的sql语句

		for (Map<String, Object> map : findAll) {// 迭代每行map

			// 提取
			if (matching(map.get("QUESTION"), data)) {
				// 如果问题匹配到了数据库中的问题那么久把此问题对应的答案都放进list里
				list.add(map.get("ANSWER"));
			}
			int size = list.size();// 获取list的大小

			if (size > 0) {
				Random random = new Random();
				int nextInt = random.nextInt(size);// 随机list下标（随机选择回答）
				return (String) list.get(nextInt);
			}
		}
		return "咦，我不太明白";
	}

	/**
	 * 用正则匹配用户输入的问题
	 * 
	 * @param object
	 * @param data
	 * @return
	 */
	private boolean matching(Object object, String data) {
		String question = (String) object;
		Pattern compile = Pattern.compile(question);
		Matcher matcher = compile.matcher(data);
		if (matcher.find()) {
			return true;
		}
		return false;
	}
}
